﻿<%@ WebHandler Language="C#" Class="MfgorderCompleteRecord" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Net;
using ReportBusiness;

/**
 * Description: 订单完成报表
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * Date:2022.3.22
 **/

public class MfgorderCompleteRecord : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);//查询
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "exportExcel":
                        exportExcel(jObject);//导出
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    string getSearchSqlString(JObject jObject)
    {
        string sql = @"
SELECT cci.mfgordername,mfg.qty mfgqty,cci.familylistnames,cci.productname,cci.productdescription,
       cci.containername,
       e.fullname starter,
       c.originalqty,
       DECODE(cci.isinstore,0,cci.qty,0) wipqty,
       DECODE(cci.isinstore,1,cci.qty,0) completeqty,
       NVL(sc.scrapqty,0) scrapQty,
       cci.workflowstepname,cci.fromworkcentername,cci.plannedcompletiondate,
       CASE WHEN cci.workflowstepname = '完工入库' THEN c.lastactivitydate ELSE NULL END completeDate,
       cid.createdate,
       CASE WHEN cci.sendmaterialdate IS NOT NULL THEN cci.sendmaterialdate
            WHEN cci.materialdate IS NOT NULL THEN cci.materialdate
            ELSE cci.techniquedate 
       END containerstartDate,
       c.originalstartdate,
       CASE WHEN cid.tjmng >= 1 THEN round((NVL(cid.zychgsl,0) / cid.tjmng) * 100,2) || '%' ELSE '' END yicitijiaohegelv,
       CASE WHEN cid.tjmng >= 1 THEN round((NVL(cid.zhgsl,0) / cid.tjmng) * 100,2) || '%' ELSE '' END tijiaohegelv,
       cci.sendmaterialdate,cci.materialdate,cci.techniquedate,c.militarytype
FROM mfgorder mfg 
INNER JOIN containercurrentinfo cci ON mfg.mfgorderid = cci.mfgorderid
LEFT JOIN containerinstore cid ON cid.charg = cci.containername AND cid.aufnr = mfg.mfgordername AND cid.isuse = 0
LEFT JOIN container c ON c.containerid = cci.containerid
LEFT JOIN starthistorydetail shd on shd.containerid = cci.containerid
LEFT JOIN employee e ON e.employeeid = shd.startemployeeid
LEFT JOIN 
(
    SELECT t.containerid,SUM(t.scrapqty) scrapqty
    FROM
    (
        SELECT c.containerid,qhd.qty scrapqty
        FROM qtyhistorydetails qhd
        LEFT JOIN container c ON c.containerid = qhd.containerid
        LEFT JOIN containercurrentinfo cci ON cci.containerid = c.containerid
        WHERE qhd.changeqtytype = 2 AND qhd.changecount = 1 AND c.containerid <> c.containername ";

        // 订单号
        if (jObject["mfgordername"] != null && jObject["mfgordername"].ToString() != "")
        {
            sql += string.Format(" AND cci.mfgordername = '{0}'", jObject["mfgordername"].ToString());
        }

        // 图号
        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND cci.productname = '{0}'", jObject["productname"].ToString());
        }

        // 流水卡号
        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            sql += string.Format(" AND cci.containername = '{0}'", jObject["containername"].ToString());
        }

        sql += @"

        UNION ALL

        SELECT c.containerid,ABS(cr.qty) scrapqty
        FROM CheckQtyChangeRecord cr
        LEFT JOIN container c ON c.containerid = cr.containerid
        LEFT JOIN containercurrentinfo cci ON cci.containerid = cr.containerid
        WHERE cr.isuse = 0 AND cr.changeqtytype = 2 ";

        // 订单号
        if (jObject["mfgordername"] != null && jObject["mfgordername"].ToString() != "")
        {
            sql += string.Format(" AND cci.mfgordername = '{0}'", jObject["mfgordername"].ToString());
        }

        // 图号
        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND cci.productname = '{0}'", jObject["productname"].ToString());
        }

        // 流水卡号
        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            sql += string.Format(" AND cci.containername = '{0}'", jObject["containername"].ToString());
        }

        sql += @"
    ) t
    GROUP BY t.containerid
) sc ON sc.containerid = cci.containerid
WHERE cci.containerstatus <> 2
";
        // 分厂
        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND cci.originalfactoryid = '{0}'", jObject["factoryid"].ToString());
        }

        // 工区过滤
        if (jObject["workcenterid"] != null && jObject["workcenterid"].ToString() != "")
        {
            sql += string.Format(" AND cci.fromworkcenterid = '{0}'", jObject["workcenterid"].ToString());
        }

        // 开卡人
        if (jObject["starter"] != null && jObject["starter"].ToString() != "")
        {
            sql += string.Format(" AND shd.startemployeeid = '{0}'", jObject["starter"].ToString());
        }

        // 开卡时间
        if (jObject["startdate"] != null && jObject["startdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["startdate"].ToString());
            if (arr.Count == 2)
            {
                sql += string.Format(" AND TRUNC(c.originalstartdate) >= TO_DATE('{0}','yyyy-mm-dd')", arr[0].ToString());
                sql += string.Format(" AND TRUNC(c.originalstartdate) <= TO_DATE('{0}','yyyy-mm-dd')", arr[1].ToString());
            }
        }

        // 机型
        if (jObject["productfamilyname"] != null && jObject["productfamilyname"].ToString() != "")
        {
            sql += string.Format(" AND cci.familylistnames LIKE '%{0}%'", jObject["productfamilyname"].ToString());
        }

        // 订单号
        if (jObject["mfgordername"] != null && jObject["mfgordername"].ToString() != "")
        {
            sql += string.Format(" AND cci.mfgordername = '{0}'", jObject["mfgordername"].ToString());
        }

        // 图号
        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND cci.productname = '{0}'", jObject["productname"].ToString());
        }

        // 流水卡号
        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            sql += string.Format(" AND cci.containername = '{0}'", jObject["containername"].ToString());
        }

        //完工时间
        if (jObject["finishdate"] != null && jObject["finishdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["finishdate"].ToString());
            if (arr.Count == 2)
            {
                sql += string.Format(" AND cci.workflowname = 'FMW' AND TRUNC(c.lastactivitydate) >= TO_DATE('{0}','yyyy-mm-dd')", arr[0].ToString());
                sql += string.Format(" AND TRUNC(c.lastactivitydate) <= TO_DATE('{0}','yyyy-mm-dd')", arr[1].ToString());
            }
        }

        //入库时间
        if (jObject["instoredate"] != null && jObject["instoredate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["instoredate"].ToString());
            if (arr.Count == 2)
            {
                sql += string.Format(" AND TRUNC(cid.createdate) >= TO_DATE('{0}','yyyy-mm-dd')", arr[0].ToString());
                sql += string.Format(" AND TRUNC(cid.createdate) <= TO_DATE('{0}','yyyy-mm-dd')", arr[1].ToString());
            }
        }

        // 订单计划完成日期
        if (jObject["planfinishdate"] != null && jObject["planfinishdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["planfinishdate"].ToString());
            if (arr.Count == 2)
            {
                sql += string.Format(" AND TRUNC(mfg.plannedcompletiondate) >= TO_DATE('{0}','yyyy-mm-dd')", arr[0].ToString());
                sql += string.Format(" AND TRUNC(mfg.plannedcompletiondate) <= TO_DATE('{0}','yyyy-mm-dd')", arr[1].ToString());
            }
        }

        return sql;
    }

    //查询方法
    Result getData(JObject jObject)
    {
        Result r = new Result();
        string sql = getSearchSqlString(jObject);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //导出
    void exportExcel(JObject jObject)
    {
        string sql = getSearchSqlString(jObject);
        DataTable dtResult = dal.GetDataTable(sql);

        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        
        dtResult.Columns.Remove("sendmaterialdate");
        dtResult.Columns.Remove("materialdate");
        dtResult.Columns.Remove("techniquedate");
        
        dtResult.Columns["mfgordername"].Caption = "订单号";
        dtResult.Columns["mfgqty"].Caption = "订单数量";
        dtResult.Columns["familylistnames"].Caption = "型别";
        dtResult.Columns["productname"].Caption = "零件图号";
        dtResult.Columns["productdescription"].Caption = "零件名称";
        dtResult.Columns["containername"].Caption = "流水卡号";
        dtResult.Columns["starter"].Caption = "批次开卡人";
        dtResult.Columns["originalqty"].Caption = "开卡数";
        dtResult.Columns["wipqty"].Caption = "在制数";
        dtResult.Columns["completeqty"].Caption = "完工数";
        dtResult.Columns["scrapQty"].Caption = "报废数";
        dtResult.Columns["workflowstepname"].Caption = "当前工序";
        dtResult.Columns["fromworkcentername"].Caption = "责任工区";
        dtResult.Columns["plannedcompletiondate"].Caption = "计划完成时间";
        dtResult.Columns["completeDate"].Caption = "完成时间";
        dtResult.Columns["createdate"].Caption = "入库时间";
        dtResult.Columns["containerstartDate"].Caption = "开卡时间";
        dtResult.Columns["yicitijiaohegelv"].Caption = "一次提交合格率";
        dtResult.Columns["tijiaohegelv"].Caption = "提交合格率";
        dtResult.Columns["originalstartdate"].Caption = "实际开卡时间";
        dtResult.Columns["militarytype"].Caption = "军种";
        ExportHelper.ExportExcel(dtResult, "订单完成报表");
    }
}